package domein;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Logger;

/**
 * 
 * @author rensbonnez
 * The TCP sender.
 * 
 */

public class TCPSender extends Thread
{
	public static Logger logger = Logger.getLogger("MyLog");
	final int bufferSize = Settings.getMaxFileSize();
	private File peerFile;
	
	private Socket uploadSocket;
	private FileInputStream inputStream;
	private DataOutputStream outputStream;
	
	public TCPSender(Socket uploadSocket)
	{
		setUploadSocket(uploadSocket);
	}
	
	@Override
	public void run() 
	{
		try 
		{
			logger.info("=============UPLOADING FILE=============");
			Scanner scanner = new Scanner(uploadSocket.getInputStream());
			int fileId = Integer.parseInt(scanner.nextLine());
			
			peerFile = new File(PeerController.getInstance().getPeerFileWithId(fileId).getFilePad());
			inputStream = new FileInputStream(peerFile);
			outputStream = new DataOutputStream(uploadSocket.getOutputStream());
			
			byte[] data = new byte[bufferSize];
			int read = 0;
			
			while ((read = inputStream.read(data)) != -1) 
			{
				outputStream.write(data, 0, read);
				outputStream.flush();
			}
			
			logger.info("File is succesfully uploaded.");
			
			outputStream.close();
			inputStream.close();
			uploadSocket.close();
		} 
		catch (FileNotFoundException e)
		{
			logger.info("File cannot download, file not found or directory doesn't exist.");
			
			try
			{
				outputStream.close();
				inputStream.close();
				uploadSocket.close();
			}
			catch (IOException e1)
			{
				logger.info("Failed to close connection");
			}
		}
		catch (SocketException e)
		{
			logger.info("The connection with the download-host is broken.");
			
			try
			{
				outputStream.close();
				inputStream.close();
			}
			catch (IOException e1)
			{
				logger.info("Failed to close connection");
			}
		}
		catch (IOException e) 
		{
			e.printStackTrace();
			
			try
			{
				outputStream.close();
				inputStream.close();
				uploadSocket.close();
			}
			catch (IOException e1)
			{
				logger.info("Failed to close connection");
			}
		}
	}
	
	/**
	 * 
	 * Getters & Setters
	 *
	 */

	public int getBufferSize() {
		return bufferSize;
	}

	public Socket getUploadSocket() {
		return uploadSocket;
	}

	public void setUploadSocket(Socket uploadSocket) {
		this.uploadSocket = uploadSocket;
	}

	public File getPeerFile() {
		return peerFile;
	}

	public void setPeerFile(File peerFile) {
		this.peerFile = peerFile;
	}
}